
const { PostItem, User } = require('../db')
const { Op } = require('sequelize');

const typeMap = {
    0: '公告',
    1: '失物招领',
    2: '意见反馈',
}
// 新建postItem
exports.createPostItem = async (req, res) => {
    const { id } = req.user
    const { content, type, imgUrls } = req.body;
    const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '年').replace(/-/g, '月') + '日';
    try {
        const postItem = await PostItem.create({
            content,
            date: dateStr,
            type: typeMap[type],
            userId: id,
            statu: 0,
            imgUrls,
            // UserId !!!!
            UserId: id
        });
        // const tempUser = await User.findOne({ where: { id: id } });
        if (postItem)
            res.send({
                status: 200,
                message: '帖子发出成功！',
            });
        else {
            res.send({
                status: 500,
                message: '帖子发出失败！',
            })
        }
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 分页查询，获取pageSize, pageNum，type，statu，content

exports.getPostItems = async (req, res) => {

    const { pageSize, pageNum, type, statu, content } = req.body;
    try {
        //支持通过content模糊查询postItem
        const postItems = await PostItem.findAll({
            where: {
                type: typeMap[type],
                statu,
                content: {
                    [Op.like]: `%${content}%` // 使用 Op.like 进行模糊查询
                },
            },
            order: [['date', 'DESC']],
            include: [{
                model: User,
                attributes: ['username', 'avatarUrl']
            }],
            limit: pageSize,
            offset: (pageNum - 1) * pageSize,
        })
        // console.log(postItems);
        const postItemsRes = postItems.map((item) => {
            return {
                id: item.id,
                type: item.type,
                content: item.content,
                statu: item.statu,
                date: item.date,
                username: item.User.username,
                avatarUrl: item.User.avatarUrl,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
            }
        })
        // // 根据postItems中的userId找到对应的username和avatarUrl
        // for (let i = 0; i < postItems.length; i++) {
        //     const user = await User.findOne({ where: { id: postItems[i].userId } });
        //     postItems[i].dataValues.avatarUrl = user.avatarUrl;
        //     postItems[i].dataValues.username = user.username;
        // }
        const resTotal = await PostItem.count({
            where: {
                type: typeMap[type],
                statu,
                content: {
                    [Op.like]: `%${content}%` // 使用 Op.like 进行模糊查询
                }
            }
        })
        res.send({
            status: 200,
            message: '获取帖子成功！',
            data: postItemsRes,
            total: resTotal
        })
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }

}

// 根据id获取postItem
exports.getPostItemById = async (req, res) => {
    const { id } = req.query;
    if (!id) {
        return res.status(400).send({
            status: 400,
            message: '缺少必要的id参数'
        });
    }
    // console.log('sbid', id);

    try {
        const postItem = await PostItem.findOne({
            where: {
                id: parseInt(id),
            },
        });
        if (postItem) {
            // postItem.dataValues.comments = comments;
            const user = await User.findOne({
                where: { id: postItem.UserId }
            })
            const postDetail = {
                ...postItem.dataValues,
                avatarUrl: user.dataValues.avatarUrl,
                username: user.dataValues.username,
            }
            res.send({
                status: 200,
                message: '获取帖子成功！',
                data: postDetail,
            })
        }
        else {
            res.send({
                status: 404,
                message: '帖子不存在！',
            })
        }
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 根据id删除postItem
exports.deletePostItemById = async (req, res) => {
    const { id } = req.params;
    try {
        const postItem = await PostItem.findOne({
            where: {
                id,
            },
        });
        if (postItem) {
            await PostItem.destroy({
                where: {
                    id,
                },
            });
            res.send({
                status: 200,
                message: '删除帖子成功！',

            })
        }
        else {
            res.send({
                status: 404,
                message: '帖子不存在！',
            })
        }
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 通过id修改postItem的statu（审核）
exports.updatePostItemStatu = async (req, res) => {
    const { id, statu } = req.body;
    const { id: userId } = req.user;
    try {
        const user = await User.findOne({
            where: {
                id: userId,
            },
        });
        if (user.role === 'jyu_admin') {
            const postItem = await PostItem.findOne({
                where: {
                    id,
                },
            });
            if (postItem) {
                await PostItem.update({
                    statu,
                }, {
                    where: {
                        id,
                    },
                });
                res.send({
                    status: 200,
                    message: '帖子状态修改！',
                })
            }
            else {
                res.send({
                    status: 404,
                    message: '帖子不存在！',
                })
            }
        }
        else {
            res.send({
                status: 403,
                message: '权限不足！',
            })
        }
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 根据用户id、statu、获取postItem分页列表
exports.getPostItemByUserId = async (req, res) => {
    // statu 可能为空
    const { id: userId } = req.user;
    const { statu, pageNum, pageSize } = req.body;
    console.log(statu, pageNum, pageSize);
    const offset = (pageNum - 1) * pageSize;
    if (statu === 'all') {
        try {
            const resTotal = await PostItem.count({
                where: {
                    userId,
                },
            });
            const postItems = await PostItem.findAll({
                where: {
                    userId,
                },
                include:
                    [{
                        model: User,
                        attributes: ['username', 'avatarUrl'],
                    }],
                offset,
                limit: pageSize,
            })
            const postItemsRes = postItems.map((item) => {
                return {
                    content: item.content,
                    statu: item.statu,
                    date: item.date,
                    username: item.User.username,
                    avatarUrl: item.User.avatarUrl,
                }
            })
            if (postItems.length > 0) {
                res.send({
                    status: 200,
                    message: '获取个人发布的帖子成功！',
                    data: postItemsRes,
                    total: resTotal,
                })
            }
        }
        catch (error) {
            console.error(error);
            res.status(500).send('内部服务器错误');
        }
    }
    else if (statu === 0) {
        //待审核需要验证身份
        const userInfo = await User.findOne({
            where: {
                id: userId,
            },
        })
        if (userInfo.role === 'jyu_admin') {
            try {
                const resTotal = await PostItem.count({
                    where: {
                        statu,
                    },
                });
                const postItems = await PostItem.findAll({
                    where: {
                        statu,
                    },
                    include:
                        [{
                            model: User,
                            attributes: ['username', 'avatarUrl'],
                        }]
                })
                const postItemsRes = postItems.map((item) => {
                    return {
                        id: item.id,
                        content: item.content,
                        statu: item.statu,
                        date: item.date,
                        username: item.User.username,
                        avatarUrl: item.User.avatarUrl,
                    }
                })
                res.send({
                    status: 200,
                    message: '获取审核列表成功！',
                    data: postItemsRes,
                    total: resTotal,
                })
            } catch (error) {
                console.error(error);
                res.status(500).send('内部服务器错误');
            }
        }
    }
}